import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    searchKeyword: '',
    currentFilter: 'all',
    projectList: []
  },

  onLoad(options) {
    this.loadProjectList()
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.loadProjectList()
  },

  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter
    this.setData({
      currentFilter: filter
    })
    this.loadProjectList()
  },

  loadProjectList() {
    // 调用获取项目列表接口
    post(apiPaths.getProjects).then(res => {
      if (res.code === 200) {
        // 处理项目数据
        let projects = res.data || []
        
        // 根据搜索关键词过滤
        if (this.data.searchKeyword) {
          projects = projects.filter(project => 
            project.name.includes(this.data.searchKeyword) || 
            project.description.includes(this.data.searchKeyword)
          )
        }

        // 根据筛选条件过滤
        if (this.data.currentFilter === 'open') {
          projects = projects.filter(project => project.status === '进行中')
        } else if (this.data.currentFilter === 'archived') {
          projects = projects.filter(project => project.status === '已归档')
        } else if (this.data.currentFilter === 'mine') {
          // 这里可以根据实际需求过滤我的项目
          // 暂时显示所有项目
        }
        
        // 添加状态样式类
        projects = projects.map(project => {
          return {
            ...project,
            statusClass: project.status === '进行中' ? 'open' : 'archived'
          }
        })

        this.setData({
          projectList: projects
        })
      } else {
        wx.showToast({
          title: res.message || '获取项目列表失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '获取项目列表失败',
        icon: 'none'
      })
    })
  },

  onProjectTap(e) {
    const projectId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/projectDetail/projectDetail?id=${projectId}`
    })
  },

  onCreateProject() {
    wx.navigateTo({
      url: '/pages/projectDetail/projectDetail?action=create'
    })
  }
})